#include <iostream>
#include <algorithm>
#include <cstring>
#define MAXN 2005
#define INF 1 << 30
using namespace std;
int height[MAXN], N, ordered_height[MAXN];
int dp[MAXN][MAXN];

void solve();

int main() {
    cin >> N;
    for (int i = 0; i < N; i++)
        cin >> height[i];
    solve();
}


void solve() {
    memcpy(ordered_height, height, sizeof height);
    sort(ordered_height, ordered_height + N);
    int len = unique(ordered_height, ordered_height + N) - ordered_height;
    for (int i = 0; i < N; i++) {
        int temp = INF;
        for (int j = 0; j < len; j++) {
            temp = min(temp, dp[i][j]);
            dp[i + 1][j] = abs(height[i] - ordered_height[j]);
            dp[i + 1][j] += temp;
        }
    }

    int res = INF;
    for (int i = 0; i < len; i++) res = min(res, dp[N][i]);
    cout << res << endl;

}